package org.atlantis.net.base.vote;

import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;

import org.atlantis.net.base.frame.Framer;
import org.atlantis.net.base.frame.LengthFramer;

/*
 * 投票服务端。
 */
public class VoteServerTCP {

	public static final int SERVER_PORT = 10006;

	public static void main(String[] args) throws Exception {
		ServerSocket socket = new ServerSocket(SERVER_PORT);
		System.out.println("Vote Server started on: " + SERVER_PORT);
		VoteMessageCoder coder = new VoteMessageBinCoder();
		VoteService service = new VoteService();

		while (true) {
			Socket client = socket.accept();
			SocketAddress address = client.getRemoteSocketAddress();
			System.out.println("Handling vote at " + address);
			Framer framer = new LengthFramer(client.getInputStream());
			byte[] req;
			while ((req = framer.nextMessage()) != null) {
				System.out.println("Received message (" + req.length
						+ " bytes)");
				VoteMessage message = service.handleRequest(coder.decode(req));
				framer.frameMessage(coder.encode(message),
						client.getOutputStream());
			}
			client.close();
		}
	}
}
